import { Table, Pagination, Tooltip } from 'antd'
import './index.less'
import { useState } from 'react'
interface Props {
  rowKey?(record: any): any
  extra?: string | React.ReactNode
  dataSource?: any
  columns?: any
  scroll?: Record<string, number | string>
  loading?: boolean
  isSelection?: boolean
  selectRows?: (...set: any) => void
  onRow?: (...set: any) => Record<string, any>
  pagination?: {
    pageSize: number | undefined
    total: number | undefined
    current: number
    onChange: (page: number, pageSize: number) => void
  }
}
// 防止频繁创建 缓存使用
let canvas: any = null
let context: any = null
export default function CustomTable(props: Props) {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const onSelectChange = (selectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(selectedRowKeys)
    if (props.isSelection && typeof props.selectRows === 'function') {
      props.selectRows(selectedRowKeys, setSelectedRowKeys)
    }
  }
  const rowSelection = props.isSelection
    ? {
        selectedRowKeys,
        preserveSelectedRowKeys: true,
        onChange: onSelectChange,
      }
    : undefined

  const { dataSource, loading, columns, scroll, pagination, onRow } = props

  // 定义一个辅助函数，用于检查渲染内容是否为空白字符串
  const isRenderContentEmpty = (data: any) => {
    if (typeof data === 'string') {
      return data.trim().length <= 0
    }
  }
  // 计算文字宽度
  const getTextWidth = (text: string | number, font = '14px BlinkMacSystemFont') => {
    if (typeof text === 'number') text = text.toString()
    if (!canvas) canvas = document.createElement('canvas')
    if (!context) context = canvas.getContext('2d') as any
    context.font = font
    const textmetrics = context.measureText(text)
    return textmetrics.width
  }
  //render为jsx时手动判断加'-'
  const newColumns = columns?.map((item: Record<string, any>) => {
    const data = {
      ellipsis: {
        showTitle: false,
      },
      ...item,
      render: (text: any, ...set: any) => {
        const renderContent = item?.render ? item?.render(text, ...set) : text
        if (renderContent === 0) return 0 //除去年龄特殊情况0不过滤
        if (!renderContent) return '-' //没有值返回占位符
        if (isRenderContentEmpty(renderContent)) return '-' //空白字符串返回占位符
        if (
          item.width &&
          (typeof renderContent === 'string' || typeof renderContent === 'number') &&
          getTextWidth(renderContent) > item.width - 15
        ) {
          // 15是table内容的padding
          return (
            <Tooltip placement="topLeft" title={renderContent}>
              {renderContent}
            </Tooltip>
          )
        }
        return renderContent // 返回原始文本
      },
    }
    return data
  })

  return (
    <div className="custom_table_style">
      <div className="table_extra" style={{ display: props?.extra ? 'block' : 'none' }}>
        {props?.extra}
      </div>
      <Table
        className="table_wrap_box"
        dataSource={dataSource}
        columns={newColumns}
        scroll={{
          x: scroll?.x ?? window.innerWidth - 230 - 60,
        }}
        pagination={false}
        loading={loading}
        rowSelection={rowSelection}
        rowKey={props.rowKey === undefined ? (record) => record.id : props.rowKey}
        onRow={onRow}
      />
      {pagination && (
        <Pagination
          total={pagination.total}
          current={pagination.current}
          pageSize={pagination.pageSize || 10}
          onChange={(page, pageSize) => pagination.onChange!(page, pageSize)}
          showSizeChanger={true}
          showTitle={true}
          showTotal={(total) => `共 ${total} 条`}
          style={{ textAlign: 'center', marginTop: 12 }}
          pageSizeOptions={[10, 15, 20, 30]}
        />
      )}
    </div>
  )
}
